package com.lpf.xpermission;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.lpf.xypermission.annotation.PermissionCanceled;
import com.lpf.xypermission.annotation.PermissionDenied;
import com.lpf.xypermission.annotation.PermissionNeed;


public class MainActivity extends AppCompatActivity {

    private String tag = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.bt_request_permission).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

//                requestPermissionAop();

                PermissionUtil.getInstance().writeFile();

            }
        });
    }


    @PermissionNeed(permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode = 10)
    public void requestPermissionAop() {

        Log.e(tag, "requestPermissionAop>>>>>>");
    }

    @PermissionCanceled
    public void permissionCanceled(int requestcode) {

        Log.e(tag, "permissionCanceled>>>>>>" + requestcode);
    }

    @PermissionDenied
    public void permissionDenied(int requestcode) {

        Log.e(tag, "permissionDenied>>>>>>" + requestcode);

    }


    public void requestPermission() {

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {

            Log.e(tag, "权限已授予》1");

        } else {


            Log.e(tag, "权限被拒绝》1");

            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {


                Log.e(tag, "shouldShowRequestPermissionRationale>>>>>");

            } else {

                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2);
                Log.e(tag, "requestPermissions>>>>>");

            }

        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            Log.e(tag, "权限已授予》2");
        } else {

            Log.e(tag, "权限被拒绝》2");
        }

    }
}